package com.example.core.service.helper;

import com.alibaba.fastjson.JSONObject;
import org.springframework.stereotype.Component;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import javax.annotation.Resource;

@Component
public class RedisHelper {

    @Resource
    private JedisPool jedisPool;

    private Jedis getJedis() {
        return jedisPool.getResource();
    }

    public <T> T get(String key, Class<T> clazz) {
        Jedis jedis = getJedis();
        return JSONObject.parseObject(jedis.get(key), clazz);
    }

    public Long incr(String key) {
        Jedis jedis = getJedis();
        return jedis.incr(key);
    }

    public <T> String set(String key, T value) {
        Jedis jedis = getJedis();
        return jedis.set(key, JSONObject.toJSONString(value));
    }

    public <T> String set(String key, T value, Long seconds) {
        Jedis jedis = getJedis();
        String result = jedis.set(key, JSONObject.toJSONString(value));
        jedis.expire(key, seconds);
        return result;
    }

    public <T> Long setNx(String key, String val) {
        Jedis jedis = getJedis();
        return jedis.setnx(key, val);
    }

    public <T> Long setNx(String key, String val, Long seconds) {
        Jedis jedis = getJedis();
        Long setnx = jedis.setnx(key, val);
        jedis.expire(key, seconds);
        return setnx;
    }

    public <T> Long del(String... keys) {
        Jedis jedis = getJedis();
        return jedis.del(keys);
    }

}
